/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrameAparato.java
 *
 * Created on Sep 17, 2012, 6:23:09 PM
 */
package ar.com.wholeconsulting.pacc.gui.aparatos;

import ar.com.wholeconsulting.pacc.gui.aparatos.ensayos.FrameEnsayo;
import ar.com.wholeconsulting.pacc.gui.modelos.UsuarioCheckboxFinder;
import ar.com.wholeconsulting.pacc.gui.utils.frame.SaveOnCloseDialog;
import ar.com.wholeconsulting.pacc.gui.utils.table.JCheckboxCellRenderer;
import ar.com.wholeconsulting.pacc.gui.utils.treetable.modelos.ModelosTreeTableNode;
import ar.com.wholeconsulting.pacc.gui.utils.treetable.Ensayos.EnsayosTreeTableModel;
import ar.com.wholeconsulting.pacc.gui.utils.treetable.PACCAbstractTreeTableModel;
import ar.com.wholeconsulting.pacc.gui.utils.treetable.modelos.ModelosSelectableTreeTableModel;
import ar.com.wholeconsulting.pacc.model.Aparato;
import ar.com.wholeconsulting.pacc.model.Fabricante;
import ar.com.wholeconsulting.pacc.model.Usuario;
import ar.com.wholeconsulting.pacc.model.ensayos.Ensayo;
import ar.com.wholeconsulting.pacc.model.ensayos.MedicionEspesor;
import ar.com.wholeconsulting.pacc.model.ensayos.PruebaHidraulica;
import ar.com.wholeconsulting.pacc.model.ensayos.PruebaNeumatica;
import ar.com.wholeconsulting.pacc.persistance.JPASession;
import java.awt.Frame;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.text.JTextComponent;

/**
 *
 * @author pable
 */
public class FrameAparato extends SaveOnCloseDialog {
    
    private PACCAbstractTreeTableModel modelosTreeTableModel;
    private PACCAbstractTreeTableModel ensayosTreeTableModel = new EnsayosTreeTableModel();
    private Aparato currentAparato;

    /**
     * Creates new form FrameAparato
     */
    public FrameAparato(Frame parent) {
        super(parent, true);
        currentAparato = new Aparato();
        isNew = true;
        modelosTreeTableModel = new ModelosSelectableTreeTableModel(currentAparato);
        initComponents();
        initComponentsView();
        
    }
    
    public FrameAparato(Frame parent, Aparato aparato) {
        super(parent, true);
        currentAparato = JPASession.getInstance().geGenericstSingleResultNamedQuery(Aparato.class, Aparato.FIND_ALL, aparato.getId());
        modelosTreeTableModel = new ModelosSelectableTreeTableModel(currentAparato);
        initComponents();
        initComponentsViewFixed();
        
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popupAddEnsayo = new javax.swing.JPopupMenu();
        itemMedicionEspesor = new javax.swing.JMenuItem();
        itemPruebaNeumativa = new javax.swing.JMenuItem();
        itemPrubaHidraulica = new javax.swing.JMenuItem();
        jLabel2 = new javax.swing.JLabel();
        comboUsuario = new javax.swing.JComboBox();
        tabbedPanelModelos = new javax.swing.JTabbedPane();
        panelModelos = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        treeTableModelos = new org.jdesktop.swingx.JXTreeTable(modelosTreeTableModel);
        panelAtributos = new javax.swing.JPanel();
        labelDescription = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textDescripcion = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        textNumeroDeSerie = new javax.swing.JTextField();
        panelEnsayos = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        treeTabeEnsayos = new org.jdesktop.swingx.JXTreeTable(ensayosTreeTableModel);
        buttonAddEnsayo = new javax.swing.JButton();
        buttonRemoveEnsayo = new javax.swing.JButton();
        panelPerifericos = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        popupAddEnsayo.setInvoker(this);

        itemMedicionEspesor.setText("Medicion de Espesores");
        itemMedicionEspesor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemMedicionEspesorActionPerformed(evt);
            }
        });
        popupAddEnsayo.add(itemMedicionEspesor);

        itemPruebaNeumativa.setText("Prueba Neumatica");
        itemPruebaNeumativa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemPruebaNeumativaActionPerformed(evt);
            }
        });
        popupAddEnsayo.add(itemPruebaNeumativa);

        itemPrubaHidraulica.setText("Prueba Hidraulica");
        itemPrubaHidraulica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemPrubaHidraulicaActionPerformed(evt);
            }
        });
        popupAddEnsayo.add(itemPrubaHidraulica);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo Aparato");
        setResizable(false);

        jLabel2.setText("Usuario:");

        comboUsuario.setEditable(true);

        treeTableModelos.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(treeTableModelos);

        javax.swing.GroupLayout panelModelosLayout = new javax.swing.GroupLayout(panelModelos);
        panelModelos.setLayout(panelModelosLayout);
        panelModelosLayout.setHorizontalGroup(
            panelModelosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelModelosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelModelosLayout.setVerticalGroup(
            panelModelosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelModelosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                .addContainerGap())
        );

        tabbedPanelModelos.addTab("Modelos", panelModelos);

        labelDescription.setText("Descripcion:");

        textDescripcion.setColumns(20);
        textDescripcion.setRows(5);
        jScrollPane2.setViewportView(textDescripcion);

        jLabel1.setText("Numero de Serie:");

        javax.swing.GroupLayout panelAtributosLayout = new javax.swing.GroupLayout(panelAtributos);
        panelAtributos.setLayout(panelAtributosLayout);
        panelAtributosLayout.setHorizontalGroup(
            panelAtributosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelAtributosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelAtributosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
                    .addComponent(labelDescription, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textNumeroDeSerie, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelAtributosLayout.setVerticalGroup(
            panelAtributosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelAtributosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelDescription)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textNumeroDeSerie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        tabbedPanelModelos.addTab("Atributos", panelAtributos);

        treeTabeEnsayos.getTableHeader().setReorderingAllowed(false);
        jScrollPane3.setViewportView(treeTabeEnsayos);

        buttonAddEnsayo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/report2_(add)_16x16.gif"))); // NOI18N
        buttonAddEnsayo.setToolTipText("Agregar Modelo");
        buttonAddEnsayo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddEnsayoActionPerformed(evt);
            }
        });

        buttonRemoveEnsayo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/report2_(delete)_16x16.gif"))); // NOI18N
        buttonRemoveEnsayo.setToolTipText("Editar Modelo");
        buttonRemoveEnsayo.setEnabled(false);
        buttonRemoveEnsayo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRemoveEnsayoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelEnsayosLayout = new javax.swing.GroupLayout(panelEnsayos);
        panelEnsayos.setLayout(panelEnsayosLayout);
        panelEnsayosLayout.setHorizontalGroup(
            panelEnsayosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEnsayosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelEnsayosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
                    .addGroup(panelEnsayosLayout.createSequentialGroup()
                        .addComponent(buttonAddEnsayo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonRemoveEnsayo)))
                .addContainerGap())
        );
        panelEnsayosLayout.setVerticalGroup(
            panelEnsayosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEnsayosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelEnsayosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonAddEnsayo)
                    .addComponent(buttonRemoveEnsayo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
                .addContainerGap())
        );

        tabbedPanelModelos.addTab("Ensayos", panelEnsayos);

        panelPerifericos.setRequestFocusEnabled(false);

        javax.swing.GroupLayout panelPerifericosLayout = new javax.swing.GroupLayout(panelPerifericos);
        panelPerifericos.setLayout(panelPerifericosLayout);
        panelPerifericosLayout.setHorizontalGroup(
            panelPerifericosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 444, Short.MAX_VALUE)
        );
        panelPerifericosLayout.setVerticalGroup(
            panelPerifericosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 502, Short.MAX_VALUE)
        );

        tabbedPanelModelos.addTab("Perifericos", panelPerifericos);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/save_16x16.gif"))); // NOI18N
        jButton2.setToolTipText("Guardar/Guardar Cambios");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/trash_16x16.gif"))); // NOI18N
        jButton1.setToolTipText("Descartar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tabbedPanelModelos, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboUsuario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(comboUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabbedPanelModelos)
                .addContainerGap())
        );

        tabbedPanelModelos.getAccessibleContext().setAccessibleName("Modelos");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonAddEnsayoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddEnsayoActionPerformed
        popupAddEnsayo.setLocation(buttonAddEnsayo.getLocationOnScreen());
        popupAddEnsayo.setVisible(true);
}//GEN-LAST:event_buttonAddEnsayoActionPerformed
    
    private void buttonRemoveEnsayoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRemoveEnsayoActionPerformed
}//GEN-LAST:event_buttonRemoveEnsayoActionPerformed
    
    private void itemMedicionEspesorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemMedicionEspesorActionPerformed
        popupAddEnsayo.setVisible(false);
        Ensayo ensayo = new MedicionEspesor();
        addEnsayo(ensayo);
    }//GEN-LAST:event_itemMedicionEspesorActionPerformed
    
    private void itemPruebaNeumativaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemPruebaNeumativaActionPerformed
        popupAddEnsayo.setVisible(false);
        Ensayo ensayo = new PruebaNeumatica();
        addEnsayo(ensayo);
    }//GEN-LAST:event_itemPruebaNeumativaActionPerformed
    
    private void itemPrubaHidraulicaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemPrubaHidraulicaActionPerformed
        popupAddEnsayo.setVisible(false);
        Ensayo ensayo = new PruebaHidraulica();
        addEnsayo(ensayo);
    }//GEN-LAST:event_itemPrubaHidraulicaActionPerformed
    
    private void addEnsayo(Ensayo ensayo) {
        JFrame frame = new FrameEnsayo(currentAparato, ensayo);
        frame.setVisible(true);
        ((EnsayosTreeTableModel) treeTabeEnsayos.getTreeTableModel()).addEnsayo(currentAparato, ensayo);
        treeTabeEnsayos.updateUI();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAddEnsayo;
    private javax.swing.JButton buttonRemoveEnsayo;
    private javax.swing.JComboBox comboUsuario;
    private javax.swing.JMenuItem itemMedicionEspesor;
    private javax.swing.JMenuItem itemPrubaHidraulica;
    private javax.swing.JMenuItem itemPruebaNeumativa;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel labelDescription;
    private javax.swing.JPanel panelAtributos;
    private javax.swing.JPanel panelEnsayos;
    private javax.swing.JPanel panelModelos;
    private javax.swing.JPanel panelPerifericos;
    private javax.swing.JPopupMenu popupAddEnsayo;
    private javax.swing.JTabbedPane tabbedPanelModelos;
    private javax.swing.JTextArea textDescripcion;
    private javax.swing.JTextField textNumeroDeSerie;
    private org.jdesktop.swingx.JXTreeTable treeTabeEnsayos;
    private org.jdesktop.swingx.JXTreeTable treeTableModelos;
    // End of variables declaration//GEN-END:variables

    private void initComponentsView() {
        List<Object> list = JPASession.getInstance().getResultListNamedQuery(Usuario.FIND_ALL);
        for (Object user : list) {
            this.comboUsuario.addItem(user);
        }
        
        JTextComponent editor = (JTextComponent) this.comboUsuario.getEditor().getEditorComponent();
        editor.setDocument(new UsuarioCheckboxFinder(this.comboUsuario));
        
        list = JPASession.getInstance().getResultListNamedQuery(Fabricante.FIND_ALL);
        for (Object fabricante : list) {
            if (((Fabricante) fabricante).getModelos().size() > 0) {
                modelosTreeTableModel.addToRoot(new ModelosTreeTableNode((Fabricante) fabricante));
            }
        }
        treeTableModelos.getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
        treeTableModelos.getColumn(3).setCellRenderer(new JCheckboxCellRenderer());
        treeTableModelos.updateUI();
    }
    
    private void initComponentsViewFixed() {
        comboUsuario.addItem(currentAparato);
        comboUsuario.setSelectedItem(currentAparato);
        comboUsuario.setEnabled(false);
        
        modelosTreeTableModel.addToRoot(new ModelosTreeTableNode(currentAparato.getModelo().getFabricante()));
        treeTableModelos.setEnabled(false);
        
        ((EnsayosTreeTableModel) treeTabeEnsayos.getTreeTableModel()).addEnsayosToRoot(currentAparato);
        treeTabeEnsayos.updateUI();
        
        textDescripcion.setText(currentAparato.getDescripcion());
        textNumeroDeSerie.setText(currentAparato.getNumeroDeSerie());
    }
    
    @Override
    protected void saveNewObjects() {
        if (isNew) {
            JPASession.getInstance().getManager().persist(currentAparato);
        }
    }
}
